<template>
  <div class="favorite-question-container">
    <!-- 筛选区域 -->
    <div class="filter-area">
      <!-- 标题区 -->
    <div class="favorite-title-area">
      <h3 class="favorite-title">我的收藏题目</h3>
    </div>
      <div class="filter-content">
        <div class="filter-row">
          <div class="filter-label">课程与知识点</div>
          <el-cascader
            v-model="selectedCourseAndKnowledge"
            :options="courseKnowledgeOptions"
            :props="cascaderProps"
            clearable
            placeholder="请选择课程和知识点"
            @change="handleCourseKnowledgeChange"
            class="filter-input"
          />
        </div>
        <div class="filter-row">
          <div class="filter-label">时间范围</div>
          <el-date-picker
            v-model="timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            class="filter-input"
          />
        </div>
        <div class="filter-actions">
          <el-button type="primary" @click="handleFilter">筛选</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="practiceAllFiltered" :disabled="filteredQuestions.length === 0">练习全部</el-button>
        </div>
      </div>
    </div>
    <!-- 收藏题目列表 -->
    <div class="question-list-area">
      <div class="list-header">
        <div class="header-left">
          <span class="total-count">共 {{ totalQuestions }} 道收藏题</span>
        </div>
        <div class="header-right">
          <el-button type="success" size="small" :disabled="filteredQuestions.length === 0" @click="practiceAllFiltered">
            练习全部
          </el-button>
        </div>
      </div>
      <div class="list-view">
        <el-table :data="filteredQuestions" style="width: 100%" border stripe>
          <el-table-column prop="course_name" label="课程" width="120" />
          <el-table-column prop="point_name" label="知识点" width="150" />
          <el-table-column prop="question_content" label="题目内容">
            <template #default="{ row }">
              <div class="question-content" v-html="row.question_content"></div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handlePractice(scope.row)">
                去练习
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="totalQuestions"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10, 20, 50]"
          background
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { useUserStore } from '../../../store/UserStore'
import { ElMessage } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()
const userId = computed(() => userStore.userInfo?.userId)

const courseKnowledgeOptions = ref<any[]>([])
const cascaderProps = { checkStrictly: true, expandTrigger: 'hover' }
const selectedCourseAndKnowledge = ref([])
const timeRange = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalQuestions = ref(0)
const allQuestions = ref<any[]>([])

const fetchCoursesAndPoints = async () => {
  const courseRes = await axios.get('http://localhost:8080/Courses/all')
  const courses = courseRes.data
  const cascaderData = await Promise.all(
    courses.map(async (course: any) => {
      const kpRes = await axios.get('http://localhost:8080/KnowledgePoint/course', { params: { courseId: course.courseId } })
      return {
        value: course.courseId,
        label: course.courseName,
        children: kpRes.data.map((kp: any) => ({
          value: kp.pointId,
          label: kp.pointName
        }))
      }
    })
  )
  courseKnowledgeOptions.value = cascaderData
}

const fetchFavoriteQuestions = async () => {
  let params: any = {
    userId: userId.value
  }
  if (selectedCourseAndKnowledge.value.length > 0) {
    params.courseId = selectedCourseAndKnowledge.value[0]
    if (selectedCourseAndKnowledge.value.length > 1) {
      params.pointId = selectedCourseAndKnowledge.value[1]
    }
  }
  if (timeRange.value && timeRange.value.length === 2) {
    params.startTime = timeRange.value[0]
    params.endTime = timeRange.value[1]
  }
  const res = await axios.get('http://localhost:8080/favorites/query', { params })
  allQuestions.value = res.data
  totalQuestions.value = res.data.length
}

const filteredQuestions = computed(() => {
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  return allQuestions.value.slice(start, start + pageSize.value)
})

const handleCourseKnowledgeChange = () => {}
const handleFilter = () => { currentPage.value = 1; fetchFavoriteQuestions() }
const handleReset = () => {
  selectedCourseAndKnowledge.value = []
  timeRange.value = ''
  currentPage.value = 1
  fetchFavoriteQuestions()
}
const handleSizeChange = (size: number) => { pageSize.value = size; fetchFavoriteQuestions() }
const handleCurrentChange = (page: number) => { currentPage.value = page; fetchFavoriteQuestions() }

const handlePractice = (row: any) => {
  router.push({ name: 'FavoriteQuestionPractice', query: { favoriteId: row.favoriteId } })
}
const practiceAllFiltered = () => {
  if (filteredQuestions.value.length === 0) {
    ElMessage.warning('没有可练习的收藏题目')
    return
  }
  const ids = filteredQuestions.value.map(q => q.favoriteId).join(',')
  router.push({ name: 'FavoriteQuestionPractice', query: { favoriteId: ids } })
}

onMounted(() => {
  fetchCoursesAndPoints()
  if (userId.value) fetchFavoriteQuestions()
})
</script>

<style scoped lang="scss">
.favorite-question-container {
  padding: 24px 10px 24px 10px;
  background: linear-gradient(135deg, #e7eef9 0%, #cae0f8 100%);
  min-height: 100vh;
  position: relative;
}

.filter-area {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  padding: 28px 32px 22px 32px;
  margin-bottom: 28px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid #d4e6f7;
  position: relative;
  z-index: 1;
  
  .filter-content {
    display: flex;
    gap: 22px;
    max-width: 1100px;
    margin: 0 auto;
    flex-wrap: wrap;
    align-items: flex-end;
  }
  
  .filter-row {
    display: flex;
    align-items: center;
    min-width: 0;
    margin-right: 10px;
    
    .filter-label {
      width: 80px;
      font-size: 14px;
      color: #4a5568;
      white-space: nowrap;
      margin-right: 18px;
      font-weight: 500;
    }
    
    .filter-input {
      flex: 1;
      min-width: 0;
      max-width: 180px;
      background: #fff;
      border-radius: 8px;
      border: 1px solid #d4e6f7;
      
      :deep(.el-input__inner) {
        &:focus {
          border-color: #4a90e2;
        }
      }
    }
  }
  
  .filter-actions {
    display: flex;
    gap: 12px;
    
    .el-button {
      border-radius: 8px;
      font-size: 14px;
      min-width: 70px;
      height: 36px;
      transition: all 0.3s ease;
      
      &.el-button--primary {
        background: #4a90e2;
        color: white;
        border: none;
        
        &:hover {
          background: #3a7bc8;
          transform: translateY(-2px);
        }
      }
      
      &.el-button--success {
        background: #486ebb;
        color: white;
        border: none;
        
        &:hover {
          background: #385da1;
          transform: translateY(-2px);
        }
      }
      
      &:not(.el-button--primary):not(.el-button--success) {
        background: #f0f8ff;
        color: #4a90e2;
        border: 1px solid #d4e6f7;
        
        &:hover {
          background: rgba(74, 144, 226, 0.1);
          color: #3a7bc8;
          transform: translateY(-2px);
        }
      }
    }
  }
}

.question-list-area {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  padding: 28px 22px 22px 22px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid #d4e6f7;
  position: relative;
  z-index: 1;
  
  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 22px;
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 16px;
      
      .total-count {
        font-size: 15px;
        color: #4a5568;
        font-weight: 500;
      }
    }
    
    .header-right {
      display: flex;
      align-items: center;
      gap: 14px;
      
      .el-button {
        border-radius: 8px;
        font-size: 14px;
        min-width: 70px;
        height: 36px;
        background: #486ebb;
        color: white;
        border: none;
        transition: all 0.3s ease;
        
        &:hover {
          background: #385da1;
          transform: translateY(-2px);
        }
        
        &:disabled {
          background: #cbd5e0;
          cursor: not-allowed;
        }
      }
    }
  }
  
  .list-view {
    :deep(.el-table) {
      background: transparent;
      border-radius: 8px;
      border: 1px solid #d4e6f7;
      
      .question-content {
        line-height: 1.5;
      }
      
      .el-table__cell {
        padding: 10px 0;
        border-color: #d4e6f7;
      }
      
      .el-button + .el-button {
        margin-left: 14px !important;
      }
    }
  }
  
  .pagination {
    margin-top: 28px;
    display: flex;
    justify-content: center;
  }
  
  :deep(.el-table .el-button) {
    border-radius: 8px !important;
    font-size: 14px !important;
    min-width: 70px;
    height: 36px;
    background: #4a90e2 !important;
    color: white !important;
    border: none !important;
    transition: all 0.3s ease;
    
    &:hover {
      background: #3a7bc8 !important;
      transform: translateY(-2px);
    }
  }
}

.favorite-title-area {
  display: flex;
  align-items: flex-end;
  gap: 24px;
  margin-bottom: 18px;
  padding-left: 8px;
}

.favorite-title {
  font-size: 25px;
  color: #2c5282;
  font-family: 'Comic Sans MS', 'PingFang SC', 'Microsoft YaHei', cursive, sans-serif;
  font-weight: bold;
  letter-spacing: 2px;
  margin: 0;
}

.favorite-desc {
  font-size: 16px;
  color: #718096;
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  margin-bottom: 2px;
}
</style>